package admin

import (
	"encoding/json"
	"fmt"
	"net/http"
	"xmshop-gin/models"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

type LoginController struct {
	BaseController
}

func (con LoginController) Index(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/login/login.html", gin.H{})
}

func (con LoginController) Captcha(c *gin.Context) {
	id, b64s, err := models.MakeCaptcha(34, 100, 2)

	if err != nil {
		fmt.Print(err)
	}

	c.JSON(http.StatusOK, gin.H{
		"captchaId":  id,
		"captchaImg": b64s,
	})
}

func (con LoginController) DoLogin(c *gin.Context) {
	captchaId := c.PostForm("captchaId")
	username := c.PostForm("username")
	password := c.PostForm("password")
	verifyValue := c.PostForm("verifyValue")

	//1、判断验证码是否正确
	if flag := models.VerifyCaptcha(captchaId, verifyValue); flag {
		// 2、查询数据库 判断用户以及密码是否存在
		userInfoList := []models.Manager{}
		password = models.Md5(password)

		models.DB.Where("username=? AND password=?", username, password).Find(&userInfoList)
		if len(userInfoList) > 0 {
			// 3、执行登录 保存用户信息 执行跳转
			session := sessions.Default(c)
			// 注意：session.Set没法直接保存结构体对应的切片 把结构体转换成json字符串
			userInfoSlice, _ := json.Marshal(userInfoList)
			session.Set("userInfo", string(userInfoSlice))
			session.Save()
			con.Success(c, "登录成功", "/admin")
		} else {
			con.Error(c, "用户名或者密码错误", "/admin/login")
		}
	} else {
		con.Error(c, "验证码验证失败", "/admin/login")
	}
}

func (con LoginController) logout(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete("userInfo")
	session.Save()
	con.Success(c, "退出登录成功", "/admin/login")
}

func (con LoginController) LoginOut(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete("userinfo")
	session.Save()
	con.Success(c, "退出登录成功", "/admin/login")
}
